var fs = require("fs");
var piexif = require("./piexif.js");
var http = require('http');
//require("//api.map.baidu.com/api?v=3.0&ak=BA7a941611feddd5977215b8b08afbb8")

function Get(src, cb)
{
	http.get(src, function(res){
		let err;
		const { statusCode } = res;
		let rawData = "";

		if (!statusCode === 200) 
			err = new Error("服务器响应失败");
		if (!/application\/json/.test(res.headers["content-type"]))
			 err = new Error("数据格式错误，需要json格式");
		if (err) {
			console.log(err);
			//释放内存
			res.resume();
			return;
		}

		// chunk是16进制BUFFER数据，需要转成字符打印
		res.on("data", (chunk) => {
			rawData += chunk;
		});

		//监听请求结束
		res.on("end", () => {
			try {
				//console.log(rawData);
				cb(rawData);
			} catch (e) {
				console.log(e);
			}
		});
	});
}

function DoOne()
{
	if (!data[i].endsWith("jpg") && !data[i].endsWith("jpeg") && !data[i].endsWith("JPG") && !data[i].endsWith("JPEG"))
	{
		i++;
		if (i < data.length)
			DoOne();
		return;
	}
	//console.log(data[i]);
	
	filecon = fs.readFileSync("image\\" + data[i], 'binary');
    exif = piexif.load(filecon);
	dt = exif['Exif'][piexif.ExifIFD.DateTimeOriginal];
	dt2 = exif['0th'][piexif.ImageIFD.DateTime];
	//console.log(dt);
	//console.log(exif['0th']);
	
	//if (dt == undefined || dt[16] != ":")
	{
		//console.log("no dt, ", dt);
		
		var s = "";
		var dateS = "";
		var lng = "";
		var lat = "";
		var state = "";
		for (var j = 0; j < data[i].length; j++)
		{
			if ((data[i][j]) == "2" && state == "")
				state = "date";
			if (state == "date" && data[i][j] == "(")
				state = "lng";
			if (state == "lng" && data[i][j] == ",")
				state = "lat";
			if (state == "lat" && data[i][j] == ")")
				break;
			
			if (state == "date")
				dateS += data[i][j];
			if (state == "lng" && data[i][j] != "(")
				lng += data[i][j];
			if (state == "lat" && data[i][j] != ",")
				lat += data[i][j];
		}
		//console.log(dateS, lng, lat);
		
		var dateS2 = dateS.substring(0, 4) + ":" + dateS.substring(4, 6) + ":" +  dateS.substring(6, 8) + " ";
		
		if (dt == undefined)
			dateS2 += "12:00:00";
		else
			dateS2 += dt.substring(11, 16) + ":" + dt.substring(17, 19);
		
		while (dateS2.length < 19)
			dateS2 += "0";
		
		//console.log(dateS2);
		new_dt = dateS2;
	}
	Get("http://restapi.amap.com/v3/assistant/coordinate/convert?locations=" + lng + "," + lat + "&coordsys=gps&output=json&key=5539eed681745c6bf6a89a43838929a7", function(data){
		data = JSON.parse(data);
		Get("http://restapi.amap.com/v3/geocode/regeo?output=json&location=" + data.locations + "&key=5539eed681745c6bf6a89a43838929a7&radius=0&extensions=base", function(data){
			data = JSON.parse(data);
			//var r = data.result[0];
			//var x = r.x;
			//var y = r.y;
			newLng = lng;
			newLat = lat;
			
			DoOne2(data.regeocode.addressComponent);
		});	
	});	
}

function DoOne2(info)
{
	/*var oldLng = exif['GPS'][piexif.GPSIFD.GPSLongitude];
	var oldLat = exif['GPS'][piexif.GPSIFD.GPSLatitude];
	if (oldLng != undefined)
		oldLng = piexif.GPSHelper.dmsRationalToDeg(oldLng);
	else
		oldLng = 10000;
	if (oldLat != undefined)
		oldLat = piexif.GPSHelper.dmsRationalToDeg(oldLat);
	else
		oldLat = 10000;
	console.log(oldLng, oldLat);
	
	if (dt != new_dt || dt2 != new_dt || Math.abs(oldLng - newLng) > 0.001 || Math.abs(oldLat - newLat) > 0.001)
	{*/
		//if(dt[16] == ":")
	console.log(info);
	if (info.city == "")
	{
		info.city = info.province;
	}
	if (info.district == "")
	{
		info.district = info.city;
	}
	if (info.township == "")
	{
		info.township = "__";
	}
	if (info.streetNumber.street == "")
	{
		info.streetNumber.street = "__";
	}
	
	var s = info.city + info.district + info.township + info.streetNumber.street;
	
	console.log(data[i], s);
	
		/*exif['Exif'][piexif.ExifIFD.DateTimeOriginal] = new_dt;		
		exif['0th'][piexif.ImageIFD.DateTime] = new_dt;		
		var x1 = piexif.GPSHelper.degToDmsRational(newLng);
		var y1 = piexif.GPSHelper.degToDmsRational(newLat);
		console.log(x1, y1);
	    exif['GPS'][piexif.GPSIFD.GPSLongitudeRef] = "E";
	    exif['GPS'][piexif.GPSIFD.GPSLatitudeRef] = "N";
	    exif['GPS'][piexif.GPSIFD.GPSLongitude] = x1;
	    exif['GPS'][piexif.GPSIFD.GPSLatitude] = y1;
		//exif['Exif'][piexif.ExifIFD.DateTimeDigitized] = new_dt;				
		var newExifDump = piexif.dump(exif);
		var newData = piexif.insert(newExifDump, piexif.remove(filecon));*/
		fs.writeFileSync("out\\" + s + " " + dt.substring(0, 4) + dt.substring(5, 7) + dt.substring(8, 10) + "(" + Number(newLng).toFixed(6) + "," + Number(newLat).toFixed(6)+i + ").jpg", filecon, 'binary');
	//}
	
	i++;
	if (i < data.length)
		setTimeout(DoOne, 500);
}

fs.readdir("image", function (err, dat){
	if (err)
	{
		console.log(err);
	}
	else
	{
		data = dat;
		i = 0;
		DoOne();
	}
});